package com.amigo.online.provider.video.rocketmq.consumer;

import java.util.List;
import java.util.stream.Collectors;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.amigo.online.provider.video.mapper.VideoMapper;
import com.amigo.online.provider.video.model.entity.Video;
import com.amigo.online.provider.video.mongo.dao.VideoDao;
import com.amigo.online.provider.video.rocketmq.PushMessage;
import com.amigo.online.provider.video.rocketmq.model.BaseMqSendModel;

import tk.mybatis.mapper.entity.Example;

@Component("DropVideoComsumer")
public class DropVideoComsumer implements PushMessage {
    @Autowired
    private VideoMapper videoMapper;
    @Autowired
    private VideoDao videoDao;

    private static final Logger log = LoggerFactory.getLogger(DropVideoComsumer.class);

    @Override
    public void handleMessage(BaseMqSendModel baseMqSendModel) {
        log.info("------------------------------定时删除视频----------------------------");
        // 当前时间24小时之前
        long time = System.currentTimeMillis() / 1000 - 24 * 60 * 60;
        Example example = new Example(Video.class);
        example.createCriteria().andCondition("destroy = 1").andCondition("deleted = 0")
                .andCondition("created_time < " + time);
        List<Video> rs = videoMapper.selectByExample(example);
        if (!rs.isEmpty()) {
            List<Long> ids = rs.stream().map(video -> video.getId()).collect(Collectors.toList());
            log.info("删除的视频ID:{}", ids);
            Example update = new Example(Video.class);
            update.createCriteria().andIn("id", ids);
            Video record = new Video();
            record.setDeleted(1);
            record.setDeletedTime(System.currentTimeMillis() / 1000);
            videoMapper.updateByExampleSelective(record, example);
            videoMapper.deleteByExample(update);
			
			/* 异步处理
			 * videoDao.deleteVideoByIds(ids);
			
			// 照顾方法兼容，只能这么写
			List<String> idsStr = new ArrayList<>();
			for (Long id : ids) {
				idsStr.add(String.valueOf(id));
			}

			// 同步solr
		    JSONObject obj = new JSONObject();
			obj.put("id", idsStr);
			RocketMqUtil.send(new BaseMqSendModel.Builder()
								.beanName("VideoDeleteToSolrConsumer")
								.sendContentBean(obj)
								.tag(MqTag.SEARCH)
								.build());
			log.info("删除的视频成功");*/
        }

    }

}
